﻿
using Max.PH6_2006A.LowCode.Domain;
using Max.PH6_2006A.LowCode.IService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Data;
using System.IdentityModel.Tokens.Jwt;

namespace Max.PH6_2006A.LowCode.API.Controllers
{
    /// <summary>
    /// 讲课测试时用的控件器
    /// </summary>
    [Route("api/[controller]")]
    //[Consumes("application/json","multipart/form-data")]
    [ApiController]
    public class TestController : ControllerBase
    {

        Microsoft.AspNetCore.Hosting.IWebHostEnvironment _host;
        IEmployeeService _employeeService;
        public TestController(Microsoft.AspNetCore.Hosting.IWebHostEnvironment host, IEmployeeService employeeService)
        {
            _host = host;
            _employeeService = employeeService;
        }

        #region Token test

        [HttpGet("token")]
        public IActionResult SimplCreateToken()
        {
            ////1、创建一个token对象
            //var token = new JwtSecurityToken(issuer:"lcg",audience:"lcg",claims:null,notBefore:null,expires:null,signingCredentials:null);
            ////2、生成token
            //var jwtToke = new JwtSecurityTokenHandler().WriteToken(token);


            System.Security.Claims.Claim[] claims = new System.Security.Claims.Claim[] {
                 new System.Security.Claims.Claim("UserName","lcg"),
                 new System.Security.Claims.Claim("Role","Admin")
            };

            string customKey = "aflasjdfl;asfjlas;fdjlasfjas90834salfdasjlfsajflasfas";
            byte[] bt = System.Text.ASCIIEncoding.UTF8.GetBytes(customKey);

            Microsoft.IdentityModel.Tokens.SecurityKey key = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(bt);

            Microsoft.IdentityModel.Tokens.SigningCredentials signingCredentials
                = new Microsoft.IdentityModel.Tokens.SigningCredentials(key, "HS512");

            JwtSecurityToken token = new JwtSecurityToken(
                issuer: "梁才根", //签发人
                audience: "任何人", //受众
                claims: claims, //声明
                notBefore: DateTime.Now, //这在个日期之前是无效的
                expires: DateTime.Now.AddHours(2),//过期时间（2小时）             
                signingCredentials: signingCredentials //签名
            );

            var str = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler().WriteToken(token);

            return Ok(str);
        }

        #endregion

        #region File Down

        /// <summary>
        /// 文件下载
        /// </summary>
        /// <returns></returns>
        [HttpGet("download")]

        public async Task<IActionResult> DownloadFile()
        {

            var wwwrott = _host.WebRootPath;


            string filePath = $"wwwroot\\导入模板-员工信息.xlsx";
            var ms = await System.IO.File.ReadAllBytesAsync(filePath);
            return File(ms, "application/octet-stream", $"{System.DateTime.Now.ToString("yyyyMMdd")}.xlsx");
        }

        /// <summary>
        /// 文件导入
        /// </summary>
        /// <param name="forms"></param>
        /// <returns></returns>
        [HttpPost("import")]
        public IActionResult ImportFile()
        {
            string filePatn = "wwwroot\\test.xlsx";
            string wwwroot = "";
            List<ImportEmployeeModel> models = new List<ImportEmployeeModel>();

            #region 第一部分：上传Excel文件

            //1、拿到客户或用户选择要上传的文件（接收文件）
            var files = Request.Form.Files;

            if (files == null || files.Count <= 0)
                return BadRequest("请选择文件");

            var file = files[0]; //上传，我们只要一个文件

            //2、将文件保存到服务器
            //  2.1、将文件保存到哪里？
            //默认保存到wwwroot目录下（不要直接用字符串写死）
            wwwroot = _host.WebRootPath;
            
            //服务器的文件路径   wwwroot/1.xls
            filePatn = wwwroot + file.FileName;

            //  2.2、怎么保存（什么方式）? --  文件流   Stream
            using (var _stream = System.IO.File.Create(filePatn))
            {
                file.CopyTo(_stream);
            }



            #endregion

            #region 第二部分：读取上传文件的内容

            //这两个是根据excel文件版本来定义的，可以根据上传的文件的扩展名来判断
            //NPOI.XSSF
            //NPOI.HSSF

            //得到一个excel的book（工作区域)
            var stream = System.IO.File.Open(filePatn, FileMode.Open);
            var book = new NPOI.XSSF.UserModel.XSSFWorkbook(stream);

            //得这指定的sheet
            //var sheet = book.CreateSheet();
            var sheet = book.GetSheetAt(0);

            //要得到这个sheet的行和列
            //var row = sheet.CreateRow(0);
            //var cell = row.CreateCell(0);
            //cell.SetCellValue("1");

            //这个sheet的最大的行数
            int rows = sheet.LastRowNum;


            for (int i = 1; i <= rows; i++)
            {
                //这得具体的行
                var row = sheet.GetRow(i);

                ImportEmployeeModel model = new ImportEmployeeModel();
                model.Weixin = row.GetCell(13).StringCellValue;
                model.EmployeeNo = row.GetCell(1).StringCellValue; 
                model.Name = row.GetCell(2).StringCellValue;

                //身份证后6为作为登录密码
                int len = 6;
                var card =  row.GetCell(5).StringCellValue;
                //320152 199001    01 4587    //18
                model.Password = MD5Hash.Hash.Content(card.Substring(card.Length - len - 1, len));

                //model.Age =Convert.ToInt32( row.GetCell(4).StringCellValue);

                models.Add(model);
            }

            #endregion

            #region 第三部分：将内容保存到数据库

            var result = _employeeService.Execute(
                "insert into Employee(EmployeeNo,Name,Age) values(@EmployeeNo,@Name,@Age);" +
                "insert into SystemUser(LoginName,Password,NickName) values(@EmployeeNo,@Password,@Name)", models);

            #endregion


            return Ok(result);
        }


        [HttpPost("import2")]
        public IActionResult ImportFile2()
        {
            var r = Request.Form.Files;
            //上传文件
            var upload =  Max.PH6_2006A.LowCode.Common.FileHelper.FileUploadAsnyc(r);

            //读取文件内容
            var stream = System.IO.File.Open(upload.Result.Item3[0], FileMode.Open);
            var data = Max.PH6_2006A.LowCode.Common.NpoiHelper.ReadStreamToDataTable(stream);

            List<Employee> list = new List<Employee>();
            foreach (DataRow item in data.Rows)
            {
                Employee employee = new Employee();
                employee.Name = Convert.ToString(item["Name"]);
                //....
                list.Add(employee);
            }

            var result = _employeeService.Execute(
                "insert into Employee(EmployeeNo,Name,Age) values(@EmployeeNo,@Name,@Age)",
                list);


            return Ok(result);
        }


        #endregion
    }

    public class ImportEmployeeModel
    {
        public string Password { get; set; }

        //序号 工号  姓名 性别  年龄 身份证号    最高学历 籍贯  详细地址 婚否  病史 手机号 邮箱 微信号 QQ号
        public string Number { get; set; }
        public string EmployeeNo { get; set; }
        
        public string Name { get; set; }
        public string Sex { get; set; }
        public int Age { get; set; }
        public string CardNo { get; set; }
        public string Heigh { get; set; }
        public string Native { get; set; }
        public string Address { get; set; }
        public string IsMarry { get; set; }
        public string BinSi { get; set; }
        public string Phone { get; set; }
        public string Email { get; set; }
        public string Weixin { get; set; }
        public string QQ { get; set; }

    }
}
